package com.my.netty.optimize.server.service;

import com.my.netty.optimize.config.Config;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 通过接口找实现类
 */
public class ServicesFactory {

    private static final Map<Class<?>, Object> serviceMap = new HashMap<>(16);

    static {
        try (
                InputStream in = Config.class.getResourceAsStream("/application.properties")
        ) {
            Properties properties = new Properties();
            properties.load(in);
            Set<String> propertyNames = properties.stringPropertyNames();
            for (String propertyName : propertyNames) {
                if (propertyName.endsWith("Service")) {
                    //接口的Class
                    Class<?> interfaceClass = Class.forName(propertyName);
                    String value = properties.getProperty(propertyName);
                    //实现类的Class
                    Class<?> implClass = Class.forName(value);
                    //创建实现类
                    Object instance = implClass.newInstance();
                    //建立接口Class到实现类实例的关系
                    serviceMap.put(interfaceClass, instance);
                }
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError();
        }
    }

    public static <T> T getInstance(Class<T> interfaceClass) {
        return (T) serviceMap.get(interfaceClass);
    }


}
